import nativeSchema from 'utils/toolNativeSchema'

const ua = window.navigator.userAgent
var hasClickOnce = false
var openAppParams = {
  router: '',
  passprops: '',
  id: '',
  params: '',
  isRn:true,
  isunique:false,
}
export const openApp = (param: any) => {
  openAppParams = param
  console.error(param)
  var showPop = false
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
  if (!hasClickOnce) {
    hasClickOnce = true
    if (ua.toLowerCase().match(/micromessenger/i) || ua.toLowerCase().match(/WeiBo/i)) {
      // 显示弹窗
      showPop = true
    } else {
      handleOpenApp()
    }
  }
  var timer = setTimeout(() => {
    hasClickOnce = false
  }, 2000)
  return showPop
}

// 打开app
const handleOpenApp = () => {
  var schema = ''
  let params: any = ''
  let mulparams = ''
  var showPop = false
  let failUrl = '' 
  if (ua.toLowerCase().match(/micromessenger/i) || ua.toLowerCase().match(/WeiBo/i)) {
    // 显示弹窗
    showPop = true
  }
  if (openAppParams.params && openAppParams.params.length > 0) {
    //  传多个参数
    params = JSON.parse(openAppParams.params)
    for (let i in params) {
      mulparams += i + '=' + params[i] + '&'
    }
    if (mulparams.substring(mulparams.length - 1, mulparams.length) == '&') {
      mulparams = mulparams.substring(0, mulparams.length - 1)
    }
    schema = `/${openAppParams.router}?` + mulparams
  } else {
    //  传一个参数
    schema = `/${openAppParams.router}?${openAppParams.passprops}=${openAppParams.id}`
  }
  console.error(schema,'schema')
  // 唤起app失败方法替换
    
  console.log('打开app 的参数', params, ' - - schema - - :', schema)
  let path = ''
  if(openAppParams.isRn){
    path ='react-native'
    // openAppParams.isRn ?'react-native':'native'
  }else {
    if(openAppParams.isunique){
      path ='route'
    }else{
      path ='native'
    }
  }
  console.log(path,'path')
  // nativeSchema.loadSchema({
  //   // 某个schema协议，例如login,     nutritionplan
  //   schema: schema,
  //   // schema头协议,
  //   protocal: `lovelorn://${path}`,
  //   // 发起唤醒请求后，会等待loadWaiting时间，超时则跳转到failUrl，默认3000ms
  //   loadWaiting: 3000,
  //   // 唤起失败时的跳转链接，默认跳转到应用商店下载页
  //   failUrl:
  //     ua.indexOf('Android') > -1
  //       ? 'https://a.app.qq.com/o/simple.jsp?pkgname=com.yryz.lovelorn'
  //       : 'itms-apps://itunes.apple.com/cn/app/id1438503085?mt=8',
  // })
  // if(showPop){
  //   window.location.href =`lovelorn://`
  // }
  window.location.href =`lovelorn://`
  if(ua.indexOf('Android') > -1){
    failUrl = "https://a.app.qq.com/o/simple.jsp?pkgname=com.yryz.lovelorn";
  }else {
    // failUrl = "itms-apps://itunes.apple.com/cn/app/id1438503085?mt=8";
  }
  setTimeout(()=>{
    window.location.href = failUrl
  },1500)

}
